import React, { useState, useEffect, useRef } from 'react';
import { useAppStore, useProjectStore, useEditorStore, useTerminalStore, useSidebarStore } from '../../stores';
import { useMessage } from '../../hooks/useMessage';
import { Version } from '../version';
import NewProjectDialog from '../dialogs/NewProjectDialog';
import globalEventManager, { PYTHON_EVENTS } from '../../utils/eventManager';
import projectManager from '../../utils/projectManager';
import { 
  FaFolder, 
  FaPlay, 
  FaStop, 
  FaPlus, 
  FaFileImport, 
  FaFileExport, 
  FaSun, 
  FaMoon,
  FaPython,
  FaEllipsisVertical,
  FaFloppyDisk
} from 'react-icons/fa6';
import styles from './Toolbar.module.css';

const Toolbar = ({ onShowExportDialog }) => {
  const { isDarkTheme, toggleTheme } = useAppStore();
  const { 
    runCurrentFile,
    updateCurrentFileContent, 
    stopCode, 
    importProject,
    createNewProject,
    getCurrentOpenedFileId,
    getCurrentFileCode,
    getProjectName
  } = useProjectStore();
  
  const [isRunning, setIsRunning] = useState(false);
  const [showNewProjectDialog, setShowNewProjectDialog] = useState(false);
  const [showMobileMenu, setShowMobileMenu] = useState(false);
  const mobileMenuRef = useRef(null);
  const { getCurrentCode, loadContentFromFileSystem, saveNow } = useEditorStore();
  const { success, error, clearMessages } = useMessage();
  const terminalStore = useTerminalStore();
  const { fileOperations, selectedFileId } = useSidebarStore();

  const currentFileId = getCurrentOpenedFileId();
  const hasOpenFile = currentFileId && currentFileId !== -1;
  const projectName = getProjectName();

  useEffect(() => {
    const unsubscribe = globalEventManager.on(PYTHON_EVENTS.STATUS_CHANGE, (status) => {
      setIsRunning(status === 'running');
    });
    return unsubscribe;
  }, []);

  // 点击外部关闭移动端菜单
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (mobileMenuRef.current && !mobileMenuRef.current.contains(event.target)) {
        setShowMobileMenu(false);
      }
    };

    if (showMobileMenu) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [showMobileMenu]);

  const handleRun = async () => {
    if (isRunning) {
      await stopCode();
    } else {
      clearMessages();
      // 清空终端输出
      terminalStore.clearOutput();
      
      const code = getCurrentCode();
      const saveResult = await updateCurrentFileContent(code);
      
      if (!saveResult.success) {
        error(saveResult.message, { duration: 3000 });
        return;
      }
      
      const runResult = await runCurrentFile();
      
      if (!runResult.success && runResult.error !== 'RUNTIME_ERROR') {
        error(runResult.message, { duration: 3000 });
      }
    }
  };

  const handleSaveProject = async () => {
    try {
      // 导出作品为JSON
      const result = await projectManager.exportProjectAsJSON();
      console.log('导出作品结果:', result);
      
      if (result.success) {
        // 创建下载链接
        const blob = new Blob([result.data], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        
        const link = document.createElement('a');
        link.href = url;
        link.download = `${getProjectName()}.json`;
        link.style.display = 'none';
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        URL.revokeObjectURL(url);
        
        success('作品已导出为JSON文件');
      } else {
        error(result.error || '导出失败');
      }
    } catch (err) {
      error(`导出出错: ${err.message}`);
    }
  };

  const handleNewProject = () => {
    clearMessages();
    setShowNewProjectDialog(true);
  };

  const handleConfirmNewProject = async (projectName) => {
    try {
      const result = await createNewProject({
        name: projectName,
        description: '这是一个新的Python作品项目'
      });
      
      if (result.success) {
        const currentCode = await getCurrentFileCode();
        if (currentCode) {
          loadContentFromFileSystem(currentCode);
        }
        success('新作品创建成功！', { duration: 2500 });
      } else {
        error(result.message, { duration: 3000 });
      }
    } catch (err) {
      error(`创建失败: ${err.message}`, { duration: 3000 });
    }
  };

  const handleImport = () => {
    clearMessages();
    
    const input = document.createElement('input');
    input.type = 'file';
    input.multiple = false; // 暂时只支持单个文件
    input.style.display = 'none';
    
    input.onchange = async (event) => {
      const file = event.target.files?.[0];
      if (!file) {
        return;
      }
      
      try {
        // 使用侧边栏的文件导入方法，导入到当前激活位置
        const result = await fileOperations.importFile(file, selectedFileId);
        
        if (result.success) {
          success(`文件 ${file.name} 导入成功！`, { duration: 2500 });
        } else {
          error(result.error || '文件导入失败', { duration: 3000 });
        }
      } catch (err) {
        error(`导入失败: ${err.message}`, { duration: 3000 });
      }
    };
    
    document.body.appendChild(input);
    input.click();
    document.body.removeChild(input);
  };

  const handleExport = () => {
    clearMessages();
    onShowExportDialog?.();
  };

  const handleToggleTheme = () => {
    toggleTheme();
  };

  const handleToggleMobileMenu = () => {
    setShowMobileMenu(!showMobileMenu);
  };

  const handleMobileMenuAction = (action) => {
    setShowMobileMenu(false);
    action();
  };
  
  return (
    <div className={styles.toolbar}>
      <div className={styles.toolbarLeft}>
        <div className={styles.logo}>
          <FaPython className={styles.logoIcon} />
          <span className={styles.logoText}>Python</span>
        </div>
        <Version />
        {projectName && (
          <div className={styles.projectInfo}>
            <div className={styles.projectBadge}>
              <FaFolder className={styles.projectIcon} />
              <span className={styles.projectLabel}>项目</span>
              <span className={styles.projectName}>{projectName}</span>
            </div>
          </div>
        )}
      </div>
      
      <div className={styles.toolbarCenter}>
        <div className={styles.controlGroup}>
          <button 
            onClick={handleRun}
            className={`${styles.controlBtn} ${isRunning ? styles.controlBtnStop : styles.controlBtnRun}`}
            disabled={!hasOpenFile && !isRunning}
            title={!hasOpenFile && !isRunning ? '请先创建或打开一个Python文件' : ''}
          >
            {isRunning ? (
              <>
                <FaStop />
                <span>停止</span>
              </>
            ) : (
              <>
                <FaPlay />
                <span>运行</span>
              </>
            )}
          </button>
          <button 
            onClick={handleSaveProject}
            className={`${styles.controlBtn} ${styles.controlBtnSave}`}
            title="保存作品 (Ctrl+Shift+S)"
          >
            <FaFloppyDisk />
            <span>保存</span>
          </button>
        </div>
      </div>
      
      <div className={styles.toolbarRight}>
        {/* 桌面端按钮 */}
        <div className={styles.desktopButtons}>
          <button 
            onClick={handleNewProject}
            className={styles.iconBtn}
            title="新建作品"
          >
            <FaPlus />
          </button>
          <button 
            onClick={handleImport}
            className={styles.iconBtn}
            title="导入文件"
          >
            <FaFileImport />
          </button>
          <button 
            onClick={handleExport}
            className={styles.iconBtn}
            title="导出文件"
          >
            <FaFileExport />
          </button>
          <button 
            onClick={handleToggleTheme}
            className={styles.iconBtn}
            title={isDarkTheme ? '切换到亮色主题' : '切换到暗色主题'}
          >
            {isDarkTheme ? <FaSun /> : <FaMoon />}
          </button>
        </div>
        
        {/* 移动端省略按钮 */}
        <div className={styles.mobileMenu} ref={mobileMenuRef}>
          <button 
            onClick={handleToggleMobileMenu}
            className={`${styles.iconBtn} ${styles.moreBtn} ${showMobileMenu ? styles.active : ''}`}
            title="更多操作"
          >
            <FaEllipsisVertical />
          </button>
          
          {/* 移动端展开菜单 */}
          {showMobileMenu && (
            <div className={styles.mobileMenuDropdown}>
              <button 
                onClick={() => handleMobileMenuAction(handleNewProject)}
                className={styles.mobileMenuItem}
                title="新建作品"
              >
                <FaPlus />
              </button>
              <button 
                onClick={() => handleMobileMenuAction(handleImport)}
                className={styles.mobileMenuItem}
                title="导入文件"
              >
                <FaFileImport />
              </button>
              <button 
                onClick={() => handleMobileMenuAction(handleExport)}
                className={styles.mobileMenuItem}
                title="导出文件"
              >
                <FaFileExport />
              </button>
              <button 
                onClick={() => handleMobileMenuAction(handleToggleTheme)}
                className={styles.mobileMenuItem}
                title={isDarkTheme ? '切换到亮色主题' : '切换到暗色主题'}
              >
                {isDarkTheme ? <FaSun /> : <FaMoon />}
              </button>
            </div>
          )}
        </div>
      </div>
      
      {/* 新建作品弹窗 */}
      <NewProjectDialog
        isOpen={showNewProjectDialog}
        onClose={() => setShowNewProjectDialog(false)}
        onConfirm={handleConfirmNewProject}
      />
    </div>
  );
};

export default Toolbar;
